package com.shadow.study.test.study3;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;

@Slf4j
public class SyncExec {

    public static void main(String[] args) {
        log.info("ping");
        // 构建命令行
        CommandLine commandLine = CommandLine.parse("ping 127.0.0.1");

        // 接收正常结果流
        ByteArrayOutputStream successStream = new ByteArrayOutputStream();
        // 接收异常结果流
        ByteArrayOutputStream errorStream = new ByteArrayOutputStream();

        // 构造默认执行器
        DefaultExecutor executor = DefaultExecutor.builder().get();
        // 设置超时时间
        ExecuteWatchdog watchdog = ExecuteWatchdog.builder().setTimeout(Duration.ofMillis(60 * 1000)).get();
        executor.setWatchdog(watchdog);
        // 创建流处理器，用于将命令的输出重定向到指定的流
        PumpStreamHandler streamHandler = new PumpStreamHandler(successStream, errorStream);
        executor.setStreamHandler(streamHandler);

        // 执行命令
        try {
            int code = executor.execute(commandLine);
            log.info("code: {}", code);
            // 不同操作系统注意编码，否则结果乱码
            String success = successStream.toString("GBK");
            log.info("success: {}", success);
            String error = errorStream.toString("GBK");
            log.info("error: {}", error);
        } catch (IOException e) {
            log.error("发生了异常", e);
        }
    }
}
